package com.lywz.core.web.struts;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.lywz.core.EncodeConstants;
import com.lywz.core.log.LogClerk;
import com.lywz.core.util.ActionUtil;
import com.opensymphony.xwork2.ActionSupport;

/**
 * Struts Action他老爸
 * 
 * @author Lionel pang
 * 
 */
public class StrutsBase extends ActionSupport {

    private static final long serialVersionUID = 1752399295607777263L;

    protected HttpServletResponse response;

    protected HttpServletRequest request;

    public void init() {
        this.request = ServletActionContext.getRequest();
        this.response = ServletActionContext.getResponse();
    }

    /**
     * 输出json对象
     * 
     * @param obj Json对象
     */
    protected void printJsonObj(JSONObject obj) {
        String str = obj.toString();

        this.print(str);
    }

    /**
     * 重定向到制定url
     * 
     * @param url
     */
    protected void gotoUrl(String url) {
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
            LogClerk.webLog.error("gotoUrl|error|" + url, e);
        }
    }

    /**
     * 输出文本
     * 
     * @param str
     */
    protected void print(String str) {
        this.print(str, "text/html; charset=" + EncodeConstants.webEncode);
    }

    /**
     * 输出XML
     * 
     * @param str
     */
    protected void printXML(String str) {
        this.print(str, "text/xml; charset=" + EncodeConstants.webEncode);
    }

    /**
     * 按照制定contentType输出文本
     * 
     * @param str
     * @param contentType
     */
    private void print(String str, String contentType) {
        ActionUtil.print(response, str, contentType);
    }
}
